<template>
  <div class="note-detail">
    <div class="detail-header">
      <h3>便签详情</h3>
      <el-button 
        :icon="Close" 
        size="small" 
        circle 
        @click="handleClose"
      />
    </div>

    <div class="detail-content">
      <!-- 便签基本信息 -->
      <div class="info-section">
        <h4>基本信息</h4>
        <div class="info-list">
          <div class="info-item">
            <span class="label">标题:</span>
            <span class="value">{{ note.title }}</span>
          </div>
          <div class="info-item">
            <span class="label">文件夹:</span>
            <span class="value">{{ note.folder?.name || '默认分组' }}</span>
          </div>
          <div class="info-item">
            <span class="label">收藏状态:</span>
            <el-tag :type="note.isFavorite ? 'warning' : 'info'">
              {{ note.isFavorite ? '已收藏' : '未收藏' }}
            </el-tag>
          </div>
          <div class="info-item">
            <span class="label">查看次数:</span>
            <span class="value">{{ note.viewCount || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间:</span>
            <span class="value">{{ formatDate(note.createdAt) }}</span>
          </div>
          <div class="info-item">
            <span class="label">更新时间:</span>
            <span class="value">{{ formatDate(note.updatedAt) }}</span>
          </div>
          <div class="info-item" v-if="note.reminderTime">
            <span class="label">提醒时间:</span>
            <span class="value">{{ formatDate(note.reminderTime) }}</span>
          </div>
        </div>
      </div>

      <!-- 标签信息 -->
      <div class="info-section" v-if="note.tags?.length">
        <h4>标签</h4>
        <div class="tags-container">
          <el-tag 
            v-for="tag in note.tags" 
            :key="tag.id"
            :color="tag.color"
            style="margin-right: 8px; margin-bottom: 8px;"
          >
            {{ tag.name }}
          </el-tag>
        </div>
      </div>

      <!-- 便签内容预览 -->
      <div class="info-section">
        <h4>内容预览</h4>
        <div class="content-preview">
          <div v-if="note.markdownContent" class="markdown-content">
            <MdPreview
              :id="`note-preview-${note.id}`"
              :modelValue="note.markdownContent"
              :theme="previewTheme"
              language="zh-CN"
            />
          </div>
          <div v-else-if="note.content" class="html-content">
            <MdPreview
              :id="`note-content-${note.id}`"
              :modelValue="note.content"
              :theme="previewTheme"
              language="zh-CN"
            />
          </div>
          <div v-else class="empty-content">暂无内容</div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-section">
        <el-button 
          type="primary" 
          :icon="Edit"
          @click="handleEdit"
          block
        >
          编辑便签
        </el-button>
        <el-button 
          :type="note.isFavorite ? 'warning' : 'success'"
          :icon="Star"
          @click="handleToggleFavorite"
          block
        >
          {{ note.isFavorite ? '取消收藏' : '收藏便签' }}
        </el-button>
        <el-button 
          :icon="Bell"
          @click="handleSetReminder"
          block
        >
          设置提醒
        </el-button>
        <el-button 
          :icon="DocumentCopy"
          @click="handleCopy"
          block
        >
          复制便签
        </el-button>
        <el-button 
          :icon="Download"
          @click="handleExport"
          block
        >
          导出Markdown
        </el-button>
        <el-button 
          type="danger" 
          :icon="Delete"
          @click="handleDelete"
          block
        >
          删除便签
        </el-button>
      </div>
    </div>

    <!-- 设置提醒弹窗 -->
    <el-dialog 
      v-model="showReminderDialog"
      title="设置提醒"
      width="400px"
    >
      <el-form label-width="80px">
        <el-form-item label="提醒时间">
          <el-date-picker
            v-model="reminderTime"
            type="datetime"
            placeholder="选择提醒时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showReminderDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSaveReminder"
          :loading="saving"
        >
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import {
  Close, Edit, Star, Bell, DocumentCopy, Download, Delete
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/preview.css'
import { formatDate } from '@/utils/date'

// Props
interface Props {
  note: any
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'close': []
  'update': [note: any, data: any]
  'delete': [note: any]
}>()

// 响应式数据
const showReminderDialog = ref(false)
const reminderTime = ref('')
const saving = ref(false)

// Markdown 预览主题
const previewTheme = computed(() => {
  return document.documentElement.classList.contains('dark') ? 'dark' : 'light'
})

// 事件处理
const handleClose = () => {
  emit('close')
}

const handleEdit = () => {
  // TODO: 触发编辑便签
  console.log('Edit note:', props.note)
  ElMessage.info('编辑功能开发中...')
}

const handleToggleFavorite = async () => {
  try {
    const updateData = {
      isFavorite: !props.note.isFavorite
    }
    
    emit('update', props.note, updateData)
    ElMessage.success(props.note.isFavorite ? '取消收藏成功' : '收藏成功')
  } catch (error) {
    console.error('Failed to toggle favorite:', error)
    ElMessage.error('操作失败')
  }
}

const handleSetReminder = () => {
  reminderTime.value = props.note.reminderTime || ''
  showReminderDialog.value = true
}

const handleSaveReminder = async () => {
  saving.value = true
  try {
    const updateData = {
      reminderTime: reminderTime.value || null
    }
    
    emit('update', props.note, updateData)
    showReminderDialog.value = false
    ElMessage.success('提醒设置成功')
  } catch (error) {
    console.error('Failed to set reminder:', error)
    ElMessage.error('设置失败')
  } finally {
    saving.value = false
  }
}

const handleCopy = () => {
  // TODO: 实现复制便签
  console.log('Copy note:', props.note)
  ElMessage.info('复制功能开发中...')
}

const handleExport = () => {
  // TODO: 实现导出便签
  console.log('Export note:', props.note)
  ElMessage.info('导出功能开发中...')
}

const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除便签"${props.note.title}"吗？`,
      '删除便签',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    emit('delete', props.note)
    emit('close')
  } catch (error) {
    // 用户取消
  }
}
</script>

<style scoped>
.note-detail {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color-page);
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color);
}

.detail-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.detail-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.info-section {
  margin-bottom: 24px;
}

.info-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.label {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  min-width: 60px;
  flex-shrink: 0;
}

.value {
  font-size: 12px;
  color: var(--el-text-color-primary);
  flex: 1;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
}

.content-preview {
  max-height: 300px;
  overflow-y: auto;
  padding: 12px;
  background: var(--el-bg-color);
  border-radius: 8px;
  border: 1px solid var(--el-border-color);
}

.markdown-content pre {
  margin: 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-word;
}

.html-content {
  font-size: 14px;
  line-height: 1.6;
  color: var(--el-text-color-primary);
}

.empty-content {
  text-align: center;
  color: var(--el-text-color-secondary);
  font-style: italic;
}

.action-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color);
}
</style>
